import path from 'node:path';
import Koa from 'koa';
import cors from 'koa-cors';
import staticFile from 'koa-static';
import log4js from './utils/log.js';
import router from './router/index.js';

const root_dir = process.cwd();
const project_dir = path.resolve(root_dir, 'server');
console.log(`root_dir:${root_dir}; project_dir:${project_dir};`);

const log = log4js.getLogger('app');

const app = new Koa({
    proxy: true // 支持代理
});

// 支持跨域
app.use(cors());

// 判断user浏览器；设置变量
app.use(async (ctx, next) => {
    // 公共日志
    log.info(`method: ${ctx.method}; href:${ctx.href}; ip:${ctx.ip}; request.ip${ctx.request.ip};\n`);
    await next();
});

// 静态文件 https://github.com/koajs/static
app.use(staticFile(path.resolve(project_dir, './public'), { index: false }));

app.use(router.routes()).use(router.allowedMethods());

const HOST = 'localhost';
const PORT = 3001;
const server = app.listen(PORT, HOST, () => console.log(`Start: http://${HOST}:${PORT}`));
server.on('error', err => {
    log.error(err);
    throw err;
});